package com.snu.liwei.lyl_api.service;


import com.snu.liwei.lyl_api.entity.Litimg;
import com.snu.liwei.lyl_api.mapper.LitimgMapper;
import com.snu.liwei.lyl_api.request.SaveLimitingReq;
import com.snu.liwei.lyl_api.request.UploadLimitingReq;
import com.snu.liwei.lyl_api.response.LimitingPageRep;
import com.snu.liwei.lyl_api.tools.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class LitimgService {

    @Autowired
    LitimgMapper litimgMapper;

    @Autowired
    private GeneService geneService;

    @Value("${glib.case.img}")
    private String saveLimitingPath;

    @Value("${glib.path}")
    private String jsonPath;

    @Transactional(rollbackFor = Exception.class)
    public void save( UploadLimitingReq uploadLimitingReq) throws IOException {
        Date date = new Date();

        List<SaveLimitingReq> reqs = uploadLimitingReq.getReqs();
        if (!CollectionUtils.isEmpty(reqs)) {
            String gid = reqs.get(0).getgId();
            for (SaveLimitingReq req : reqs) {
                //bao存图片
                FileUtils.base64ToFile(saveLimitingPath,req.getImgBase64(),req.getgId()+"_"+req.getcId()+".png");
                //保存数据库
                litimgMapper.save(req.getgId(),req.getcId(),date,saveLimitingPath+req.getgId()+"_"+req.getcId()+".png");
            }
            //存储json模型
            String jsonStr = uploadLimitingReq.getJsonStr();
            if (!StringUtils.hasText(jsonStr)) {
                log.error("缩略图case有值，但json模型为空，gid={},参数为={}",gid,uploadLimitingReq);
                throw new RuntimeException();
            }
            String glibPath =  jsonPath +gid+".json";
            FileUtils.outFile(glibPath, jsonStr);
            //保存到gene数据库
            geneService.saveGeneJson(gid,"","",reqs.size(),glibPath);
        }

    }


    public LimitingPageRep getLimitingByPage(Integer page, Integer size, String gid) {
        //处理分页参数
        Integer start = (page-1)*size;
        List<Litimg> list= litimgMapper.getLimitingByPage(start,size,gid);

        //组装数据
        LimitingPageRep limitingPageRep = new LimitingPageRep();
        if (!CollectionUtils.isEmpty(list)) {
            limitingPageRep.setGId(gid);
            ArrayList<String> imgList = new ArrayList<>();
            for (Litimg litimg : list) {
                imgList.add(litimg.getPath());
                limitingPageRep.setImg(imgList);
            }
        }
        return limitingPageRep;
    }
}
